package com.sayice.coursetable.logic.network;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.Objects;

import okhttp3.Request;
import okhttp3.Response;

/**
 * 周相关服务
 */
public abstract class WeekService {
    private static final String WEEK_URL = "http://jwgl.csuft.edu.cn/jsxsd/jxzl/jxzl_query";

    /**
     * 获取教学周历页面
     *
     * @param username 用户名
     * @param password 密码
     * @return 返回教学周历页面的 html 字符串，若获取失败则返回 null
     */
    public static String getWeekCalendar(String username, String password) {
        return LoginService.requestHtml(username, password, httpClient -> {
            String weekCalendarHtml = null;
            Request weekRequest = new Request.Builder().url(WEEK_URL).get().build();
            try (Response weekResponse = httpClient.newCall(weekRequest).execute()) {
                String html = Objects.requireNonNull(weekResponse.body()).string();
                Elements calendarElements = Jsoup.parse(html).select("form[id=Form1]");
                if (calendarElements.size() != 0) {
                    Element calendarElement = calendarElements.get(0);
                    if (calendarElement.select("table[id=kbtable]").size() != 0) {
                        weekCalendarHtml = calendarElement.outerHtml();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return weekCalendarHtml;
        });
    }
}
